<template>
  <div class="forum-container">
    <div class="header">
      <el-button type="primary" @click="handleAdd">发帖</el-button>
    </div>

    <el-table 
      :data="forumList" 
      style="width: 100%" 
      v-loading="loading"
      :empty-text="loading ? '加载中...' : '暂无数据'"
    >
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="content" label="内容" show-overflow-tooltip />
      <el-table-column prop="username" label="发帖人" width="120" />
      <el-table-column prop="createTime" label="发布时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleReply(row)">回复</el-button>
          <el-button 
            v-if="isAdmin || row.userId === currentUserId" 
            link 
            type="danger" 
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="total > 0"
      class="pagination"
      background
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 发帖/回复对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'post' ? '发帖' : '回复'"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="标题" prop="title" v-if="dialogType === 'post'">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="form.content" :rows="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'

const userStore = useUserStore()
const isAdmin = computed(() => userStore.user?.role === 1)
const currentUserId = computed(() => userStore.user?.id)

// 所有的 ref 声明要在最前面
const loading = ref(false)
const forumList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('post')
const formRef = ref()
const currentPost = ref(null)
const form = ref({
  title: '',
  content: ''
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const loadData = async () => {
  loading.value = true
  console.log('开始加载数据...')
  try {
    const res = await request.get('/api/forum/list', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    console.log('加载数据响应:', res)
    if (res.code === 200) {
      if (Array.isArray(res.data)) {
        forumList.value = res.data
        total.value = res.data.length
      } else if (res.data && Array.isArray(res.data.records)) {
        forumList.value = res.data.records
        total.value = res.data.total
        currentPage.value = res.data.current
        pageSize.value = res.data.size
      } else {
        console.error('未知的数据结构:', res.data)
        ElMessage.error('数据格式错误')
      }
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  dialogType.value = 'post'
  form.value = {
    title: '',
    content: ''
  }
  dialogVisible.value = true
}

const handleReply = (post) => {
  dialogType.value = 'reply'
  currentPost.value = post
  form.value = {
    content: ''
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    let res
    if (dialogType.value === 'post') {
      res = await request.post('/api/forum', form.value)
    } else {
      res = await request.post(`/api/forum/${currentPost.value.id}/reply`, {
        content: form.value.content
      })
    }
    
    if (res.code === 200) {
      ElMessage.success(dialogType.value === 'post' ? '发帖成功' : '回复成功')
      dialogVisible.value = false
      loadData()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该帖子吗？', '提示', {
      type: 'warning'
    })
    const res = await request.delete(`/api/forum/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.forum-container {
  min-height: calc(100vh - 100px);
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.header {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 